package com.example.springmvcadv.config;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//HandlerInterceptor就是专门做web请求、响应的拦截器
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 请求前拦截
     * @param request Servlet的请求
     * @param response Servlet的响应
     * @param handler 包含了，当前这个请求路径匹配的Controller及方法
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取session，如果获取不到，返回null
        HttpSession session = request.getSession(false);
        if(session != null){
            String user = (String) session.getAttribute("user");
            //如果session及session中保存的用户都不为空，说明已经登录
            if(user != null){
                return true;
            }
        }
        //不允许访问
        response.setStatus(401);
        return false;
    }
}
